import {toast} from "../../utils/tool";
import {WEEK_ENUM, BASE_URL} from "../../constant/index";

const app = getApp();

const getMinutes = () => {
    const result = []
    for (let i = 0; i <= 60; i += 5) {
        result.push({
            label: `${i}分`,
            value: i
        })
    }
    return result
}
const MINUTE_COLUMN = {
    // values: [{label: '0分', value: 0,}, {label: '30分', value: 30}],
    values: getMinutes(),
    defaultIndex: 0
}
const ONE_HOUR_VALUE = 1000 * 60 * 60
Page({
    data: {
        showHourVisible: false,
        // timeDuration: 0,
        timeColumns: [],
        timePop: false,
        start_time: '00:00',
        end_time: '00:00',
        // start_time_value: 0,
        // end_time_value: 0,
        currentHour: 0,
        currentTab: 0,
        selectTime: false,
        room: {},
        store: {},
        times: {},
        allTimes: {},
        selected: [],
        select: [],
        // select_date: '',
        // select_start: '',
        // select_end: '',
        nums: 0,
        // date_arr: [],
        // date_start: '',
        // date_end: '',
        date: '',
        // showYueka: false,
        // work_data: '',
        // work_time: '',
        // aa: '',
        timeList: [{label: '2', value: 2}, {label: '3', value: 3}, {label: '4', value: 4}, {label: '其他', value: 1}],
        activeTimeID: 0,
        activeTimeText: '3',
        // ind: 1,
        // confirmTime: '',
        // confirmEndTime: '',
        roomdetail: {}, //上个页面带来的数据
        active: 0,
        weekEnum: {
            0: '周日',
            1: '周一',
            2: '周二',
            3: '周三',
            4: '周四',
            5: '周五',
            6: '周六'
        },
        weekData: {},
        totalPrice: '0.00',
        mealOptions: [],
        confirmType: 1, // 选择模式
        activeMeal: 0, // 当前选中的套餐
        timeRange: [],
        baseUrl: BASE_URL,

    },
    previewImage() {
        const {baseUrl, roomdetail} = this.data
        wx.previewImage({
            urls: [baseUrl + roomdetail.image]
        })
    },
    initTimeRange() {
        const result = []
        for (let i = 5; i < 25; i++) {
            result.push({
                label: `${i}小时`,
                value: i,
            })
        }
        this.setData({
            timeRange: result
        })
    },
    otherTime() {
        this.setData({
            showHourVisible: true
        })
    },
    selectTimeCancel() {
        this.setData({
            showHourVisible: false
        })
    },
    openTimePopup() {
        this.setData({
            timePop: true
        })
    },
    choseTimeHand(ev) {
        const {id} = ev.currentTarget.dataset
        const {activeTimeID, timeList, weekData} = this.data
        if (Number(id) === 1) {
            this.otherTime()
            return;
        }
        timeList[timeList.length - 1].label = '其他'
        if (activeTimeID === id) return
        const target = timeList.find(item => item.value === id)
        const {value} = target
        const {roomdetail: {price}} = this.data
        let totalPrice = (price * value).toFixed(2)
        const activeDate = weekData.find(item => item.active)
        const {_date} = activeDate
        const startTimeValue = new Date(`${_date} ${this.data.start_time}`).getTime()
        // const {start_time_value} = this.data
        const _time = startTimeValue + (ONE_HOUR_VALUE * target.value)
        const date = new Date(_time)
        const [h, m] = [date.getHours(), date.getMinutes()]
        const str = `${h < 10 ? '0' + h : h}:${m < 10 ? '0' + m : m}`
        this.setData({
            totalPrice,
            timeList: [...timeList],
            activeTimeID: id,
            activeTimeText: target.label,
            // end_time_value: _time,
            end_time: str,
            currentHour: value
        })
    },
    changeWeekHand(ev) {
        const {index} = ev.currentTarget.dataset
        const {weekData} = this.data
        const currentIndex = weekData.findIndex(item => item.active)
        if (currentIndex === index) return
        weekData[currentIndex].active = false
        weekData[index].active = true
        this.setData({
            weekData: [...weekData]
        })
        const target = weekData[index]
        this.initColumn(new Date(target.fullTime))
    },
    formatDate(time, isNow = false) {
        const date = new Date(time)
        const [y, m, d, w] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getDay()]
        let text = ''
        let fullTime = `${y}/${m}/${d}`
        let _date = fullTime
        if (isNow) {
            text = '今天'
            const [hour, minute] = [date.getHours(), date.getMinutes()]
            fullTime += ` ${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}`
        } else {
            text = WEEK_ENUM[w]
        }
        return {
            date: `${m >= 10 ? m : '0' + m}.${d >= 10 ? d : '0' + d}`,
            text,
            fullTime,
            active: isNow,
            _date,
        }
    },
    initWeekData() {
        const now = Date.now()
        const result = []
        const oneDay = 24 * 60 * 60 * 1000
        for (let i = 0; i < 5; i++) {
            result.push(this.formatDate(now + (oneDay * i), i === 0))
        }
        this.setData({
            weekData: result
        })
        this.initColumn(new Date())
    },
    // 门店使用教程
    jiaocheng() {
        wx.navigateTo({
            url: '/pages/jiaocheng/jiaocheng',
        })
    },
    onChange(event) {

    },

    book: function (e) {
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/book/book?id=' + id
        })
    },
    // 计算选择的开始时间
    calcOrderTime() {
        const {weekData, start_time} = this.data
        const targetDay = weekData.find(item => item.active)
        if (!targetDay) return toast({title: "日期选择错误"})
        const {_date,} = targetDay
        return `${_date} ${start_time}`
    },
    // 确定选择的时间戳
    getTimeSlot() {
        const {allTimes, currentHour} = this.data
        // const targetDay = weekData.find(item => item.active)
        // if (!targetDay) return toast({title: "时间选择错误"})
        // const {fullTime} = targetDay
        // const start = `${fullTime} ${start_time}`
        const start = this.calcOrderTime()
        if (!start) return
        const start_value = new Date(start).getTime()
        const end_value = start_value + (ONE_HOUR_VALUE * currentHour)
        const result = []
        for (const key in allTimes) {
            const target = allTimes[key]
            const {local_time} = target
            const time = new Date(local_time.replace(/\-/g, '/'))
            if (time >= start_value && time <= end_value) {
                result.push(key)
            }
        }
        return {
            result,
            date: start.replace(/\//g, '-')
        }
    },

    calcPayload() {
        const {confirmType, currentHour, roomdetail, mealOptions, activeMeal} = this.data
        const isMeal = confirmType === 0
        const data = {
            is_taocan: isMeal ? 1 : 2,
            room_id: roomdetail.id,
            nums: currentHour
        }
        if (confirmType === 0) { // 套餐
            const orderTime = this.calcOrderTime()
            data.date = orderTime.replace(/\//g, '-')
            const targetMeal = mealOptions[activeMeal]
            if (!targetMeal) return toast({title: '套餐选择有误'})
            data.taocan_id = targetMeal.id
        } else { // 小时模式
            if (currentHour < 2) return toast({title: "预定时间2小时起"})
            const {result: timeSlot, date} = this.getTimeSlot()
            if (!timeSlot.length) return toast({title: '选择时间错误'})
            data.date = date
            data.timeslot = timeSlot.join(',')
        }
        return data
    },

    confirmOrderHandler() {
        const payload = this.calcPayload()
        if (!payload) return
        // console.log(payload, 'payload')
        app.ajax({
            url: '/api/user/addordernew',
            data: payload,
            success: res => {
                if (res.code === 1) {
                    wx.redirectTo({
                        url: '/pages/unsettled/unsettled?order_id=' + res.data.id
                    })
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            }
        }, 1);
    },
    unsettled: function () {
        return this.confirmOrderHandler()
    },
    stopBubb: function () {
        return false
    },
    callPhone(e) {
        wx.makePhoneCall({
            phoneNumber: this.data.store.mobile,
            success: function () {
            },
        })
    },
    select_time: function () {
        this.openTimePopup()
    },
    close_time: function () {
        this.setData({
            selectTime: false
        });
    },
    bindDateChange: function (e) {
        var date = e.detail.value;
        this.setData({
            date: date,
            select_date: date
        })
        this.getTimes();
    },
    formatTime(time, should = true) {
        if (should) {
            time *= 1000
        }
        const date = new Date(time)
        const [h, m] = [date.getHours(), date.getMinutes()]
        const text = `${h < 10 ? '0' + h : h}:${m < 10 ? '0' + m : m}`
        return {
            text,
            value: date.getTime(),
        }
    },
    getDuration(time) {
        const {timeList} = this.data
        const target = timeList.find(item => {
            return ONE_HOUR_VALUE * item.value === time
        })
        if (target) return target.value
        return 0
    },
    pickerConfirm(ev) {
        const {currentHour} = this.data
        const {value} = ev.detail
        const [hour, minute] = value
        const {value: h, fullDate} = hour
        const {value: m} = minute
        const start_time = `${h < 10 ? '0' + h : h}:${m < 10 ? '0' + m : m}`
        const start_date = new Date(`${fullDate} ${start_time}`).getTime()
        const endTime = new Date(start_date + (currentHour * ONE_HOUR_VALUE))
        const [end_hour, end_minutes] = [endTime.getHours(), endTime.getMinutes()]
        const end_time = `${end_hour < 10 ? '0' + end_hour : end_hour}:${end_minutes < 10 ? '0' + end_minutes : end_minutes}`
        this.setData({
            start_time: start_time,
            end_time: end_time,
            // start_time_value: start_date,
            // end_time_value: endTime.getTime(),
            timePop: false,
        })
    },
    initColumn(date) {
        let [hour, y, m, d, minute] = [date.getHours(), date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getMinutes()]
        const result = []
        for (let i = hour; i < 24; i++) {
            result.push({
                label: `${i}时`,
                value: i,
                fullDate: `${y}/${m}/${d}`
            })
        }

        const nextDate = new Date(new Date(`${y}/${m}/${d} 23:59:59`).getTime() + (1000 * 10 * 10))
        const [ny, nm, nd] = [nextDate.getFullYear(), nextDate.getMonth() + 1, nextDate.getDate()]
        for (let i = 0; i < 12; i++) {
            result.push({
                label: `(次日)${i > 10 ? i : '0' + i}时`,
                value: i,
                fullDate: `${ny}/${nm}/${nd}`
            })
        }
        this.setData({
            timeColumns: [
                {
                    values: result
                },
                MINUTE_COLUMN
            ]
        })
    },
    initAllTime(id) {
        const date = new Date()
        const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
        app.ajax({
            url: '/api/index/getAllTImes',
            data: {
                id,
                date: `${year}/${month}/${day}`,
            },
            success: res => {
                if (res.code === 1) {
                    this.setData({
                        allTimes: res.data
                    })
                    // this.getTimes()
                }
            }
        }, 1);
    },
    initWeekActive(selectstart) {
        const date = new Date(selectstart * 1000)
        const {weekData} = this.data
        const [m, d] = [date.getMonth() + 1, date.getDate()]
        const str = `${m < 10 ? '0' + m : m}.${d < 10 ? '0' + d : d}`
        weekData.forEach(item => {
            item.active = str === item.date
        })
        this.setData({
            weekData: [...weekData]
        })
    },
    // 获取包间的套餐
    initMealOption(room_id, isClick) {
        app.ajax({
            url: "/api/room/roomtaocan",
            data: {room_id},
            success: resp => {
                const {code, data, msg} = resp
                if (code !== 1) return toast({title: msg})
                if (!data || !data.length) return
                const mealData = data.map(item => {
                    const {taocan_price: price, id, time} = item
                    return {price, id, time}
                })
                this.setData({
                    mealOptions: mealData,
                })
                if (isClick) {
                    const {start_time, weekData, roomdetail} = this.data
                    const activeDate = weekData.find(item => item.active)
                    const {_date} = activeDate
                    const fullTime = `${_date} ${start_time}`
                    const date = new Date(fullTime)
                    const [firstMeal] = mealData
                    if (!firstMeal) {
                        this.setData({
                            confirmType: 1,
                        })
                        return
                    }
                    const {price, time} = firstMeal
                    date.setHours(date.getHours() + time)
                    const {text} = this.formatTime(date.getTime(), false)
                    this.setData({
                        currentHour: time,
                        totalPrice: price,
                        end_time: text
                    })
                }
            }
        })
    },
    changeTimeByMeal(index) {
        const {mealOptions, weekData, start_time} = this.data
        if (index > mealOptions.length - 1) return
        const targetDate = weekData.find(item => item.active)
        if (!targetDate) return toast({title: '选择日期错误'})
        const {_date} = targetDate
        const currentDate = new Date(`${_date} ${start_time}`)
        const targetMeal = mealOptions[index]
        const {time, price} = targetMeal
        const new_time_value = currentDate.getTime() + (ONE_HOUR_VALUE * time)
        const {text} = this.formatTime(new_time_value, false)
        this.setData({
            totalPrice: Number(price),
            currentHour: time,
            // end_time_value: new_time_value,
            end_time: text,
        })
    },
    tabChange(ev) {
        console.log('tabChange')
        const {index} = ev.detail
        this.setData({
            confirmType: index
        })
        if (index === 0) {
            return this.changeTimeByMeal(this.data.activeMeal)
        }
        this.changeTimeBySelectHour()
    },
    changeTimeBySelectHour() {
        const {activeTimeID, timeList, weekData, start_time, roomdetail} = this.data
        const {price} = roomdetail
        const target = timeList.find(item => item.value === activeTimeID)
        const targetWeek = weekData.find(item => item.active)
        if (!targetWeek) return toast({title: '时间选择错误'})
        let hour = target.label.replace(/h/gi, '') * 1
        const {_date} = targetWeek
        const currentDate = new Date(`${_date} ${start_time}`)
        const new_time_value = currentDate.getTime() + (ONE_HOUR_VALUE * hour)
        const {text} = this.formatTime(new_time_value, false)
        this.setData({
            totalPrice: price * hour,
            end_time: text,
            currentHour: hour,
            // end_time_value: new_time_value,
        })
    },
    changeMeal(ev) {
        const {index} = ev.currentTarget.dataset
        if (this.data.activeMeal === index) return
        this.setData({
            activeMeal: index
        })
        this.changeTimeByMeal(index)
    },
    checkHasEndTime(roomDetail) {
        const {end_time} = roomDetail
        if (!end_time) return
        const date = new Date(end_time * 1000 + (1000 * 60 * 15))
        const [hour, minute,] = [date.getHours(), date.getMinutes()]
        const f = (v) => {
            return ('0' + v).slice(-2)
        }
        return `${f(hour)}:${f(minute)}`
    },
    onLoad: function (options) {
        const {type: joinType} = options
        const isBookTime = joinType === 'bookTime'
        const {id} = options
        this.initAllTime(id)
        // this.initMealOption(id, !isBookTime)
        this.initMealOption(id, false)
        this.initWeekData()
        this.initTimeRange()
        if (isBookTime) {
            const {selectstart, selectend} = options
            this.initWeekActive(selectstart)
            const {text: _start_time, value: _start_value} = this.formatTime(selectstart)
            const {text: _end_time, value: _end_value} = this.formatTime(selectend)
            const activeID = this.getDuration(_end_value - _start_value)
            // 计算出两个时间之间的差
            const d_value = _end_value - _start_value
            const _dur = d_value / ONE_HOUR_VALUE
            console.log(_dur, '_duration')
            const inMeal = activeID !== 0
            let _activeID = activeID
            let _text = '其他'
            const {timeList} = this.data
            if (!inMeal) {
                _activeID = 1
                _text = `${_dur}h`
                timeList[timeList.length - 1].label = `${_dur}h`
            }
            this.setData({
                start_time: _start_time,
                end_time: _end_time,
                currentHour: _dur,
                activeTimeID: _activeID,
                activeTimeText: _text,
                timeList,
                confirmType: 1,
            })
            console.log(this.data.currentHour, 'currentHour')
            let roomdetail = {}
            let totalPrice = '0.00'
            if (options.hasOwnProperty('newdata')) {
                roomdetail = JSON.parse(decodeURIComponent(options.newdata))
                roomdetail.price = Number(roomdetail.price)
                const {price} = roomdetail
                totalPrice = (Number(price) * _dur).toFixed(2)
                console.log(totalPrice, 'totalPrice')
            }
            this.setData({
                roomdetail,
                id: roomdetail.id,
                select_start: selectstart,
                select_end: selectend,
                totalPrice
            })
        } else {
            let now = new Date()
            const [year, month, day, h, m] = [now.getFullYear(), now.getMonth() + 1, now.getDate(), now.getHours(), now.getMinutes()]
            const baseDate = new Date(`${year}/${month}/${day} ${h < 10 ? '0' + h : h}:00`)
            let baseValue = baseDate.getTime()
            let [minute] = [now.getMinutes()]
            if (minute <= 30) {
                baseValue += 1000 * 60 * 30
            } else {
                baseValue += 1000 * 60 * 60
            }
            const currentDate = new Date(baseValue)
            const [_h, _m] = [currentDate.getHours(), currentDate.getMinutes()]
            let _start_time = `${_h < 10 ? '0' + _h : _h}:${_m < 10 ? '0' + _m : _m}`
            const _start_value = currentDate.getTime()
            const endTimeDate = new Date(_start_value + (ONE_HOUR_VALUE * 2))
            const [end_h, end_m] = [endTimeDate.getHours(), endTimeDate.getMinutes()]
            const _end_time = `${end_h < 10 ? '0' + end_h : end_h}:${end_m < 10 ? '0' + end_m : end_m}`
            // const _end_value = endTimeDate.getTime()
            let roomdetail = null
            let totalPrice = '0.00'
            if (options.hasOwnProperty('newdata')) {
                roomdetail = JSON.parse(decodeURIComponent(options.newdata))
                roomdetail.price = Number(roomdetail.price)
                const {price} = roomdetail
                totalPrice = (Number(price) * 2).toFixed(2)
            }
            console.log(roomdetail, 'detail')
            console.log(_start_time, _end_time, '-----time- ----')
            const endTimeText = this.checkHasEndTime(roomdetail)
            console.log(endTimeText, 'endTimeText')
            this.setData({
                roomdetail,
                start_time: endTimeText || _start_time,
                end_time: _end_time,
                // start_time_value: _start_value,
                // end_time_value: _end_value,
                currentHour: 2,
                activeTimeID: 2,
                totalPrice
            })
        }
    },
    choseTimeCancel() {
        this.setData({
            timePop: false
        })
    },
    selectTimeConfirm(ev) {
        const {value: _value} = ev.detail
        const {timeRange} = this.data
        const target = timeRange[_value * 1]
        const value = target.value
        const {roomdetail: {price}} = this.data
        const totalPrice = (value * price).toFixed(2)
        const {start_time, weekData, timeList} = this.data
        const targetDate = weekData.find(item => item.active)
        const {_date} = targetDate
        const start_time_value = new Date(`${_date} ${start_time}`).getTime()
        const _time = start_time_value + (ONE_HOUR_VALUE * value)
        const date = new Date(_time)
        const [h, m] = [date.getHours(), date.getMinutes()]
        const str = `${h < 10 ? '0' + h : h}:${m < 10 ? '0' + m : m}`
        timeList[timeList.length - 1].label = `${value}h`
        this.setData({
            totalPrice,
            timeList: [...timeList],
            activeTimeID: 1,
            activeTimeText: `${value}小时`,
            end_time_value: _time,
            end_time: str,
            currentHour: value,
            showHourVisible: false
        })
    },

})
